<template>
  <edit-dialog :centerDialogVisible="visible" tilte="变更" width="1000" @Cancel="visible=false" @Submit="handleSubmit" :defaultButton="false">
    <template #content>
      <el-form :model="form" ref="applyApproveFormRef" class="upload-approve-form">
        <div class="title">日期</div>
        <el-form-item label="开工日期" prop="date">
          <template v-if="changeField === 1">
            <el-date-picker v-model="form.newPlanStartTime" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" />
            <el-button @click="changeField = undefined" type="text" style="margin-left: 20px;">取消</el-button>
            <el-button @click="handleSubmit" :disabled="loading" type="text" style="margin-left: 20px;">确定</el-button>
          </template>
          <div v-else style="display: flex;align-items: center;">{{ form.newPlanStartTime }}
            <el-button style="margin-left: 10px" type="text" @click="handleChange(1)">变更</el-button>
          </div>
        </el-form-item>
        <el-form-item label="竣工日期" prop="date">
          <template v-if="changeField === 2">
            <el-date-picker v-model="form.newPlanEndTime" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" />
            <el-button @click="changeField = undefined" type="text" style="margin-left: 20px;">取消</el-button>
            <el-button @click="handleSubmit" :disabled="loading" type="text" style="margin-left: 20px;">确定</el-button>
          </template>
          <div v-else style="display: flex;align-items: center;">{{ form.newPlanEndTime }}
            <el-button style="margin-left: 10px" type="text" @click="handleChange(2)">变更</el-button>
          </div>
        </el-form-item>

        <div class="title">施工人员</div>
        <el-form-item label="施工单位负责人" prop="date">
          <template v-if="changeField === 3">
            <el-tree-select ref="constructionChargePersonRef" v-model="form.newConstructionChargePerson" :data="constructionChargePersonListData"
                            node-key="userId" placeholder="请选择" multiple show-checkbox check-strictly :props="personTreeProps"
                            @change="personChange"/>
            <el-button @click="changeField = undefined" type="text" style="margin-left: 20px;">取消</el-button>
            <el-button @click="handleSubmit" :disabled="loading" type="text" style="margin-left: 20px;">确定</el-button>
          </template>
          <div v-else style="display: flex;align-items: center;">{{ form.newConstructionChargePersonName }}
            <el-button style="margin-left: 10px" type="text" @click="handleChange(3)">变更</el-button>
          </div>
        </el-form-item>

        <div class="title">
          <span>特种作业人员</span>
          <template v-if="changeField===4">
            <el-button @click="changeField = undefined" type="text" style="margin-left: 20px;">取消</el-button>
            <el-button @click="handleSubmit" :disabled="loading" type="text" style="margin-left: 20px;">确定</el-button>
          </template>
          <el-button v-else @click="handleChange(4)" type="text" style="margin-left: 20px;">变更</el-button>
        </div>
        <UserTable v-for="(value, key) in specialList" :title="dicFormatter( options.specialOperationEnum, key)" :tableData="value"
                   :personType="options.personTypeEnum[0].value" @onsubmit="addUserSubmit" style="width: 800px"
                   @ondelete="deleteUser" :options="options" :disabled="changeField !== 4">
        </UserTable>

        <div class="title">其它施工人员</div>
        <UserTable title="施工人员列表" :tableData="otherConstructionUsers" :personType="options.personTypeEnum[1].value" @onsubmit="addUserSubmit"
                   style="width: 800px"
                   @ondelete="deleteUser" :options="options" :disabled="changeField !== 4" not-require-file/>
      </el-form>
    </template>
  </edit-dialog>
</template>

<script>
import EditDialog from "@/components/editDialog/index.vue";
import ApplyApproveUploadFile from "@/views/construction/project-application/review-components/ApplyApproveUploadFile";
import ApplyApproveSafeEvaluate from "@/views/construction/project-application/review-components/ApplyApproveSafeEvaluate";
import {changeProject, getProjectDetail} from "@/api/construction-project/projectManage";
import store from "@/store";
import ApplyApproveDate from "@/views/construction/project-application/review-components/ApplyApproveDate";
import {getUserInfo} from "@/api/eqpt/houseManger";
import UserTable from "@/views/construction/project-application/componens/UserTable";
import {dicFormatter} from "@/views/construction/project-application/projectUtil";

export default {
  name: "ApplyChangeDialog",
  components: {UserTable, ApplyApproveDate, ApplyApproveUploadFile, EditDialog, ApplyApproveSafeEvaluate},
  props: {},
  inject: ["options"],
  data() {
    return {
      visible: false,
      useChange: false,
      form: {
        newOperators: []
      },
      constructionChargePersonListData: [],
      personTreeProps: {
        label: 'name',
        disabled: (data, node) => {
          return false
        }
      },
      changeField: undefined,
      dicFormatter,
      loading:false
    }
  },
  computed: {
    userInfo() {
      return store.state.user.userInfo
    },
    // 施工人员
    otherConstructionUsers() {
      let users = this.form.newOperators.filter(item => item.personType === this.options.personTypeEnum[1].value)
      return users
    },
    // 特殊作业人员
    specialList() {
      let users = this.form.newOperators.filter(item => item.personType === this.options.personTypeEnum[0].value)
      let res = users.reduce((obj, item) => {
        let arr = obj[item.specialJobType]
        if (arr) {
          arr.push(item)
        } else {
          obj[item.specialJobType] = [item]
        }
        return obj
      }, {})
      if (!Object.keys(res).length) {
        return {
          UseFire: [],
        }
      } else {
        return res
      }
    },
  },
  methods: {
    parseConstructionChargePerson(str) {
      try {
        let arr = JSON.parse(str)
        return arr
      } catch (e) {
        return str ? str.split(',') : []
      }
    },
    open({row, resolve}) {
      this.useChange = undefined
      this.resolve = resolve
      getProjectDetail(row.id).then(res => {
        let {project, operators} = res.data
        this.form = {
          id: project.id,
          constructionUnit: project.constructionUnit,
          newConstructionChargePerson: this.parseConstructionChargePerson(project.constructionChargePerson),
          newConstructionChargePersonName: project.constructionChargePersonName,
          constructionTelephone: project.constructionTelephone,
          oldPlanStartTime: project.planStartTime,
          oldPlanEndTime: project.planEndTime,
          newPlanStartTime: project.planStartTime,
          newPlanEndTime: project.planEndTime,
          oldOperators: operators || [],
          newOperators: operators || [],
          updator: {
            id: this.userInfo.userId,
            name: this.userInfo.name,
            organId: this.userInfo.organId,
            organName: this.userInfo.organName,
          },
          mender: {
            id: this.userInfo.userId,
            name: this.userInfo.name,
            organId: this.userInfo.organId,
            organName: this.userInfo.organName,
          }
        }
        this.getPersonList()
      })
      this.visible = true
    },
    addUserSubmit(obj) {
      if (Array.isArray(obj)) {
        this.form.newOperators.push(...obj)
      } else {
        this.form.newOperators.push(obj)
      }
    },
    deleteUser(row) {
      let index = this.form.newOperators.find(item => item === row)
      this.form.newOperators.splice(index, 1)
    },
    handleSubmit() {
      let that = this
      that.$refs.applyApproveFormRef.validate(valid => {
        if (valid) {
          this.loading = true
          let {newConstructionChargePerson, ...more} = that.form
          // console.log({newConstructionChargePerson: JSON.stringify(newConstructionChargePerson), ...more})
          changeProject({newConstructionChargePerson: JSON.stringify(newConstructionChargePerson), ...more}).then(res => {
            that.$message.success('申请成功')
            that.resolve()
            that.visible = false
          }).finally(()=>{
            this.loading = false
          })
          this.changeField = undefined
        }
      })
    },
    handleChange(type) {
      this.changeField = type
      if (type === 3) {
        setTimeout(() => {
          this.$refs.constructionChargePersonRef.setCheckedKeys(this.form.newConstructionChargePerson)
        }, 200)
      }
    },
    getPersonList() {
      let that = this
      getUserInfo({groupIds: [that.form.constructionUnit]}).then(res => {
        that.constructionChargePersonListData = res.data
      })
    },
    personChange() {
      let ref = this.$refs.constructionChargePersonRef
      let checkedNodes = ref.getCheckedNodes()
      if (checkedNodes.length) {
        this.form.newConstructionChargePersonName = checkedNodes.map(item => item.name).join(',')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.upload-approve-form {
  height: 600px;
  overflow: auto;

  .title {
    position: relative;
    margin-bottom: 20px;
    padding-left: 13px;
    font-size: 18px;
    font-weight: 500;

    &:before {
      position: absolute;
      content: '';
      left: 0;
      top: 1px;
      height: 23px;
      border-radius: 2px;
      width: 6px;
      background: #2F7DF1;
    }
  }
}
</style>
